package com.security.customer.mobile;

import com.security.customer.CustomerUserDetailService;
import com.security.customer.handler.CustomerUsernamePasswordLoginFailureHandler;
import com.security.customer.handler.CustomerUsernamePasswordLoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @Author: TongRui乀
 * @Date: 2020-04-03 14:50
 * @description：  将自定义的短信验证码的认证流程配置到Spring Security 中 这里是单独配置 然后在securityConfig中配置到流程中
 */
@Component
public class SmsCodeAuthenticationConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private CustomerUsernamePasswordLoginSuccessHandler customerUsernamePasswordLoginSuccessHandler;

    @Autowired
    private CustomerUsernamePasswordLoginFailureHandler customerUsernamePasswordLoginFailureHandler;

    @Autowired
    private CustomerUserDetailService customerUserDetailService;

    @Override
    public void configure(HttpSecurity builder) throws Exception {

        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();

        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(customerUsernamePasswordLoginSuccessHandler);
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(customerUsernamePasswordLoginFailureHandler);
        smsCodeAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));

        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();

        smsCodeAuthenticationProvider.setCustomerUserDetailService(customerUserDetailService);

        builder.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
